package com.eastseeway.radioproject;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import com.amap.api.location.AMapLocationClient;
import com.eastseeway.commonlib_esw.utils.SoundPoolUtil;
import com.eastseeway.radioproject.RxLocation.Platform;
import com.eastseeway.radioproject.RxLocation.RxLocation;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.entities.BaseMQResponse;
import com.eastseeway.radioproject.entities.BaseTCPBean;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.BeanFromSwitchBoard;
import com.eastseeway.radioproject.entities.BeanMQLog;
import com.eastseeway.radioproject.entities.BeanOfAutoCalibration;
import com.eastseeway.radioproject.entities.BeanOfVersionInfo;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.mq.RabbitMQUtils;
import com.eastseeway.radioproject.tcp.TcpCallback;
import com.eastseeway.radioproject.tcp.TcpClient;
import com.eastseeway.radioproject.utils.ByteUtil;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.StructTransUtil;
import com.eastseeway.radioproject.utils.XLogUtils;
import com.eastseeway.radioproject.work.UploadLogWorker;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jws.thirdlibrary.CxManager;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import struct.StructException;

public class RadioApplication extends Application {

    private CxManager mJwsManager;
    private static RadioApplication instance;
    private RabbitMQUtils rabbitMQUtil;
    private TcpClient mTcpClient;

    public static RadioApplication getInstance() {
        return instance;
    }

    private static final String bindingKey = "device.parameter";

    public static Context getAppContext(){
        return instance.getApplicationContext();
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mJwsManager = CxManager.register(this, s -> {
            mJwsManager.jwsSetStatusBar(false);
            if (!mJwsManager.jwsGetEthernetState("eth0")) {
                mJwsManager.jwsSetEthernetState("eth0", true);
            }

            String ip = mJwsManager.jwsGetEthIPAddress("eth0");
            if (ip == null){
                mJwsManager.jwsSetEthStaticIPAddress("eth0",getResources().getString(R.string.ip), getResources().getString(R.string.mask), getResources().getString(R.string.gateway), getResources().getString(R.string.dns1),"");
            }
            Log.e("12121","ip: "+ip);
        });


        AMapLocationClient.updatePrivacyAgree(this, true);
        AMapLocationClient.updatePrivacyShow(this, true, true);
        RxLocation.initialize(this, Platform.TYPE_AMAP);

        Map<String,Integer> map = new HashMap<>();
//        点击提示音
        map.put("click",R.raw.sound_click);
//        治疗电极安装错误，请重新安装
        map.put("bit_6",R.raw.sound_bit_6_exception);
//        请拔掉治疗电极固定销
        map.put("bit_7",R.raw.sound_bit_7_exception);
//        请安装治疗电极
        map.put("install_electrode",R.raw.sound_install_electrode);
//        治疗电极压力过低 可能吸附不足
        map.put("pressure_low",R.raw.sound_pressure_low);
        SoundPoolUtil.getInstance().loadR(this,map);

        initTCP();
        XLogUtils.init(this);
        initMQ();
    }

    public CxManager getJwsManager(){
        return mJwsManager;
    }

    private void initMQ() {
        if (rabbitMQUtil == null) {
            rabbitMQUtil = new RabbitMQUtils(Const.MQ_HTTP_TYPE, Const.MQ_USERNAME, Const.MQ_PASSWORD,
                    getString(R.string.mq_address), Const.MQ_PORT + "", Const.MQ_VIRTUAL_HOST, Const.MQ_EXCHANGE_NAME, bindingKey, message -> {
                Type type = new TypeToken<BaseMQResponse<BeanMQLog>>() {}.getType();
                BaseMQResponse<BeanMQLog> baseMQResponse = new Gson().fromJson(message, type);
                if (baseMQResponse.getCode().equals("00001")) {
                    if (baseMQResponse.getData().getDeviceID().equalsIgnoreCase(SPHelper.getDeviceId(getAppContext()))){
                        Data inputData = new Data.Builder().putStringArray("work_key",new String[]{baseMQResponse.getData().getDataBeginDT(),baseMQResponse.getData().getDataEndDT()}).build();
                        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(UploadLogWorker.class)
                                .setInputData(inputData)
                                .build();
                        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
                    }
                }
            });
        }
    }

    public void sendData(byte[] data){
        mTcpClient.sendData(data);
    }

    private void initTCP(){

        mTcpClient = new TcpClient(getString(R.string.tcp_server_ip), Const.TCP_SERVER_PORT, new TcpCallback() {
            @Override
            public void onDataReceived(byte[] data) {
                if (data.length % Const.STANDARD_FRAME_LENGTH != 0) {
                    return;
                }
                int i = data.length / Const.STANDARD_FRAME_LENGTH;
                for (int j = 0; j < i; j++) {
                    try {
                        BaseTCPBean baseTCPBean = StructTransUtil.unpack(new BaseTCPBean(), ByteUtil.subByte(data, j * Const.STANDARD_FRAME_LENGTH, Const.STANDARD_FRAME_LENGTH));
                        int address = baseTCPBean.getAddress();
                        byte[] content = baseTCPBean.getContent();
//                        Log.e("bus data", Integer.toHexString(address) + " 总线数据： " + ByteUtil.ByteArrToHex(content));
//                        接收到来自负压手柄(手柄1)的数据
                        if (address == Const.ADDRESS_FROM_HANDLE_1_DATA_1) {
                            Bean1FromHandle bean1FromHandle = StructTransUtil.unpack(new Bean1FromHandle(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_HANDLE_1_DATA_1, bean1FromHandle));
                        } else if (address == Const.ADDRESS_FROM_HANDLE_2_DATA_1) {
//                       接收到来自非负压手柄(手柄2)的数据
                            Bean1FromHandle bean1FromHandle = StructTransUtil.unpack(new Bean1FromHandle(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_HANDLE_2_DATA_1, bean1FromHandle));
                        } else if (address == Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD) {
//                            接收到来自负压板的数据
                            BeanFromNegativePressureBoard beanFromNegativePressureBoard = StructTransUtil.unpack(new BeanFromNegativePressureBoard(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD, beanFromNegativePressureBoard));
                        } else if (address == Const.ADDRESS_FROM_BOTTOM_BOARD) {
//                            接收到来自底板的信号
                            BeanFromBottomBoard beanFromBottomBoard = StructTransUtil.unpack(new BeanFromBottomBoard(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_BOTTOM_BOARD, beanFromBottomBoard));
                        } else if (address == Const.ADDRESS_FROM_SWITCH_BOARD) {
//                            接收到来自手柄转换版的信号
                            BeanFromSwitchBoard beanFromSwitchBoard = StructTransUtil.unpack(new BeanFromSwitchBoard(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_SWITCH_BOARD, beanFromSwitchBoard));
                        } else if (address == Const.ADDRESS_FROM_HANDLE_1_DATA_3) {
//                            接收到来自负压手柄的每一针的数据，目前不做处理
//                            Bean3FromHandle bean3FromHandle = StructTransUtil.unpack(new Bean3FromHandle(), content);
//                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_HANDLE_1_DATA_3, bean3FromHandle));
                        } else if (address == Const.ADDRESS_FROM_HANDLE_2_DATA_3) {
//                            Bean3FromHandle bean3FromHandle = StructTransUtil.unpack(new Bean3FromHandle(), content);
//                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_HANDLE_2_DATA_3, bean3FromHandle));
                        } else if (address == Const.ADDRESS_FROM_ENERGY_BOARD) {
                            BeanFromEnergyBoard beanFromEnergyBoard = StructTransUtil.unpack(new BeanFromEnergyBoard(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_ENERGY_BOARD, beanFromEnergyBoard));
                        } else if (address == Const.ADDRESS_FROM_AUTO_CALIBRATION) {
//                            接收到来自自动校准工装的数据
                            BeanOfAutoCalibration beanOfAutoCalibration = StructTransUtil.unpack(new BeanOfAutoCalibration(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_FROM_AUTO_CALIBRATION, beanOfAutoCalibration));
                        } else if (address == Const.ADDRESS_VERSION_INFO_FROM_NEGATIVE_PRESSURE){
                            BeanOfVersionInfo beanOfVersionInfo = StructTransUtil.unpack(new BeanOfVersionInfo(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_VERSION_INFO_FROM_NEGATIVE_PRESSURE, beanOfVersionInfo));
                        } else if (address == Const.ADDRESS_VERSION_INFO_FROM_BOTTOM_BOARD){
                            BeanOfVersionInfo beanOfVersionInfo = StructTransUtil.unpack(new BeanOfVersionInfo(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_VERSION_INFO_FROM_BOTTOM_BOARD, beanOfVersionInfo));
                        } else if (address == Const.ADDRESS_VERSION_INFO_FROM_SWITCH_BOARD){
                            BeanOfVersionInfo beanOfVersionInfo = StructTransUtil.unpack(new BeanOfVersionInfo(), content);
                            EventBus.getDefault().post(new MessageEvent(Const.ADDRESS_VERSION_INFO_FROM_SWITCH_BOARD, beanOfVersionInfo));
                        }
                    } catch (StructException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            @Override
            public void onConnectionStateChanged(ConnectionState state) {
                EventBus.getDefault().post(new MessageEvent(Const.TCP_CONNECT_STATUS, state));
                SPHelper.saveTcpConnectStatus(getAppContext(), state == ConnectionState.CONNECTED);
                Log.e("12121", "tcp onConnectionStateChanged " + state.name());
            }

            @Override
            public void onErrorOccurred(String errorMessage) {
                Log.e("12121","tcp errorMessage "+errorMessage);
            }
        });
        mTcpClient.connect();

    }
}
